# !/usr/bin/evn python3
# -*- coding: utf-8 -*-
# File Name: auth.py
# Created Date: 2017-11-24 12:22:24
from flask import request
from app.ext import db
from app.models.user import User

def login():
    phone = request.form.get('phone', None)
    password = request.form.get("password", None)
    if not phone or not password:
        return {'msg': "手机或密码必填", 'code': 422}
    user = User.query.filter_by(phone=phone).first()
    if user and user.verify_password(password):
        token = user.generate_token
        return {'user': user.to_json(), 'token': token.decode("utf-8"), 'msg': "ok", "code": 200}
    else:
        return {'msg': " 账户或密码错误", "code": 422}


def signup():
    phone = request.form.get('phone', None)
    password = request.form.get("password", None)
    if not phone and not password:
        return {'msg': "手机或密码必填", 'code': 422}
    if password != request.form.get("confirm_password"):
        return {'msg': "两次密码不一致", "code": 422}
    ok, user = User.signup(phone=phone, password=password, name=request.form.get('name'))
    if ok:
        token = user.generate_token
        return {"user": user.to_json(), "token": token.decode("utf-8"), "msg": "ok", "code": 200}
    else:
        return {"msg": user, "code": 422}


